<?php

/*
  function: 产品模型

  create by: 徐闻洁
  create date: 2016.12.26
  description:

  modification 0.0.3
  modified by:
  description:
 * 2016/12/24 adminOrderCreate()方法里调低权限,改为普通管理员即可操作
 * 2016/12/26 getListForAdmin()修正分页功能
 * 2017/2/22  release()和close() 整合为release()
 * 2017/2/22  remove()方法加入 删除产品  相对应的detail信息和detail_option跟着删除
 * 2017/2/22  config_remove()方法里加入 删除配置 相应的config_option也跟着删除
 * 2017/2/23  reckonPrice()方法里改变demand判断 改为除了book控制器 其余都走else
 * 2017/4/24  reckonPrice方法修改获取discount
 * 2017/4/25  getList方法添加第三个参数copy 默认为0  支持分页
 * 2017/5/2   所有非查询操作加入action
 */

namespace app\common\model;

use think\Model;

class Product extends Model
{

//    protected $autoCheckFields = false;//关闭检测字段
    var $userId;
    var $demand;
    var $config;
    var $unit_id;

    function __construct()
    {
        $this->config = getConfig('product');
        //获取user_id
        if (is_null($this->userId)) {
            $userId = $this->userId = model('user')->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }

    //数组排序整理(根据字段)
    private function sortArrByField($arrUsers, $filed, $order)
    {
        $sort = array(
            'direction' => 'SORT_' . $order, //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field' => $filed,       //排序字段
        );
        $arrSort = array();
        foreach ($arrUsers AS $uniqid => $row) {
            foreach ($row AS $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if ($sort['direction']) {
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrUsers);
        }
        return $arrUsers;
    }

    //为一个“产品类”设置一个demand值
    function demand($demand)
    {
        $this->demand = $demand;
    }

    //开启单位条件
    function unit($unit_id)
    {
        if (!$unit_id) {
            $this->unit_id = 0;
            return;
        }
        $this->unit_id = $unit_id;
    }
    //品牌层brand
    //添加品牌产品
    public function add($product_type_id)
    {
        $demand = $this->demand;
        //判断必要条件是否存在
//        if (!$product_type_id > 0) {
//            return array('state' => 0, 'errormsg' => 'labels incorrect', 'errorcode' => '');
//        }
        if ($this->unit_id) {
            $data['unit_id'] = $this->unit_id;
        }
        $data['labels'] = $product_type_id;
        $data['create_time'] = time();
        $data['state'] = '2';
        $data['user_id'] = model('user')->getUserId();
        $result = db($demand)->insertGetId($data);
        if (!$result) {
            return array('state' => 0, 'errormsg' => 'insert fail');
        }
//        加入action操作
        $action=new Action;
        $action->add('创建产品');
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '',);
    }

    //品牌管理(编辑)
    public function modify($brand_id, $key, $modifyinfo)
    {
        $demand = $this->demand;
        //key检查
        $f = getConfig('product')[$demand]['modify'];
        $f = array_keys($f);
        //检查传过来的数据，KEY是否可以修改
        if (!in_array($key, $f)) {
            return array('state' => 0, 'errormsg' => 'key incorrect', 'errorcode' => '');
        }
        //id检查
        if (!($brand_id > 0)) {
            return array('state' => 0, 'errormsg' => 'brand id incorrect', 'errorcode' => '');
        }
        if($key == 'tel'){
            if(!preg_match('/0?(13|14|15|18)[0-9]{9}/', $modifyinfo)){
                return ['state'=>0,'errormsg'=>'电话号码有误'];
            }

        }
        $data[$key] = $modifyinfo;
        $brand_id = addslashes($brand_id); //sql防注入
        $where = $demand . "_id = '$brand_id'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $result = db($demand)->where($where)->update($data);
        // 记录action表动作行为
        if ($result) {
            foreach ($data as $key => $value) {
                if($key == "name"){
                    $k = "名称";
                }elseif ($key == 'imgurls'){
                    $k = "图片";
                }elseif($key == 'description'){
                    $k = '描述';
                }elseif($key == 'article'){
                    $k = '图文详情';
                }elseif($key == 'config_description'){
                    $k = '产品参数补充描述';
                }elseif ($key == 'labels'){
                    $k = '标签';
                }elseif ($key == 'highlight'){
                    $k = '置顶';
                }elseif ($key == 'unit_id'){
                    $k = '单位';
                }elseif ($key == 'homepage'){
                    $k = '主页';
                }elseif ($key == 'suggest'){
                    $k = '首页推荐';
                }elseif($key == 'spare_parts_code'){
                    $k = '图文号';
                }elseif($key == 'tel'){
                    $k = '二手车主电话';
                }elseif ($key == 'car_owner'){
                    $k = '二手车主姓名';
                }else{
                    $k = $key;
                }
                if($demand == 'mall'){
                    model('action')->add('修改产品', $k, $value,null,$brand_id);
                }else{
                    model('action')->add('修改产品', $k, $value);
                }
            }
            $ret = array('state' => 1 ,'errormsg'=>'ok');
        } else {
            $ret = array('state' => 0, 'errormsg' => 'modify error');
        }
        return $ret;
    }

    //开放 / 关闭
    function release($type_id, $release)
    {
        $demand = $this->demand;
        if (!$type_id > 0) {
            return array('state' => 0, 'errormsg' => 'brand_id incorrect', 'errorcode' => '');
        }
        if ($release == 1) {
            $data['state'] = 1;
        } else {
            $data['state'] = 2;
        }
        $where = $demand . "_id in($type_id)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $typeconfigstate = db($demand)->where($where)->update($data);
        if ($typeconfigstate) {
            $namelist = db($demand)->where($where)->select();
            $name = [];
            foreach ($namelist  as $k =>$v){
                if(isset($v['name'])){
                    $name[] = $v['name'];
                }
            }
            $name = implode(',',$name);
            if($release) {
                model('action')->add('开放产品', '产品名', $name);
            }else{
                model('action')->add('关闭产品', '产品名', $name);
            }
            return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
        }

        return array('state' => 0, 'errormsg' => 'save error', 'errorcode' => '');
    }

    //删除
    function remove($brand_id)
    {
        $demand = $this->demand;
        if (!$brand_id > 0) {
            return array('state' => 0, 'errormsg' => 'brand_id incorrect', 'errorcode' => '');
        }
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand', 'errorcode' => '');
        }
        $where = $demand . "_id in($brand_id)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['state'] = '0';
        $data['user_id'] = model('user')->getUserId();
        $res = db($demand)->where($where)->update($data);
        if($res){
            $namelist = db($demand)->where($where)->select();
            $name = [];
            foreach ($namelist as $k =>$v){
                if(isset($v['name'])){
                    $name[] = $v['name'];
                }
            }
            $name = implode(',',$name);
            if($demand == 'mall'){
                model('action')->add('删除产品','产品名称',$name);
            }else{
                model('action')->add('删除产品','产品名称');
            }

        }else{
            return ['state'=>0,'errormsg'=>'删除失败'];
        }
        //删除配置后对应的配置参数也该删除
        if ($res) {
            $detail_id = db($demand . '_detail')->where("state != 0")->where($where)->field('detail_id')->select();
            db($demand . '_detail')->where("state !=0")->where($where)->update($data);
            model('action')->add('detail_remove', $demand.'_id',$brand_id);
            foreach ($detail_id as $k => $v) {
                if ($this->unit_id) {
                    db($demand . '_detail_option')->where("detail_id = $v[detail_id] and state !=0 and unit_id = $this->unit_id")->update($data);
                } else {
                    db($demand . '_detail_option')->where("detail_id = $v[detail_id] and state !=0 ")->update($data);
                }
            }
        }
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }

    //设置高亮
    function highlight($brand_id, $cancel)
    {
        $demand = $this->demand;
        if (!$brand_id > 0) {
            return array('state' => 0, 'errormsg' => 'brand_id incorrect', 'errorcode' => '');
        }
        $where = $demand . "_id = '$brand_id'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['highlight'] = $cancel;
        $data['user_id'] = model('user')->getUserId();
        $res = db($demand)->where($where)->update($data);
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'save error');
        }
        $name = db($demand)->where($where)->find();
        $name = null;
        if(isset($name['name'])){
            $name = $name['name'];
        }
        if($cancel){
            model('action')->add('置顶', '产品名称',$name);
        }else{
            model('action')->add('取消置顶', '产品名称',$name);
        }
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }

    //admin_brand_list
    function getList($filter, $admin_only = 0,$copy = 0)
    {
        $demand = $this->demand;
        //基础条件
        $order = ["state" => "asc", 'range' => 'asc', 'create_time' => 'desc'];
        $type_id_a = $filter['select'];
        if($copy){
            $where = 'state !=0';
        }else{
            $where = 'state = 1';
        }

        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'] - 1;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        }
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        if ($filter['keywords']) {
            $where .= " and (name like '%$filter[keywords]%')";
        }
        //labels条件]
        if ($type_id_a) {
            $where .= " and labels like '%$type_id_a%'";
        }
        if(isset($pages) && isset($maxPerPage)) {
            $type_config = db($demand)->where($where)->order($order)->limit($pages * $maxPerPage,$maxPerPage)->select();
//            dump($type_config);
        }else{
            $type_config = db($demand)->where($where)->order($order)->select();
        }
        $labels_name = db($demand . '_label')->field('label_id,cn,en')->where("state = 1")->select();
//            $price = db($demand.'_detail')->where('state = 1')->order('price desc')->select();
        //再计算一次去掉不存在type_id的
        foreach ($type_config as $k => $v) {
            if (!empty($v['imgurls'])) {
                $img = explode(',', $v['imgurls'])[0];
                $type_config[$k]['imgurl'] = $img;
            }
            if ($v['state'] == 1) {
                $type_config[$k]['released'] = 1;
                unset($type_config[$k]['state']);
            }
            if ($v['labels'] != null) {
                $type_config[$k]['labels'] = explode(',', $v['labels']);
            }
            $type_config[$k]['price_min'] = $this->getPriceByProductId($v[$demand . '_id'])['price_min'];
            $type_config[$k]['price_max'] = $this->getPriceByProductId($v[$demand . '_id'])['price_max'];
            if ($admin_only) {
                $detail = $this->detail_getList(['select' => $v[$demand . '_id']], 1);
            } else {
                $detail = $this->detail_getList(['select' => $v[$demand . '_id']], 0);
            }

            $detail = $detail['data']['list'];
            $type_config[$k]['detail_amount'] = count($detail);
            if (!$type_config[$k]['detail_amount']) {
                if(!isset($pages)&&!isset($maxPerPage)) {
                    unset($type_config[$k]);
                }
            }
            $type_config[$k]['detail'] = $detail;
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels']) && $v['labels'] && is_array($v['labels'])) {
                if($type_id_a && strpos(',',$type_id_a) !== false && !in_array($type_id_a,$v['labels'])){
                    unset($type_config[$k]);
                    continue;
                }
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $type_config[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
            }
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels_name']) && isset($v['labels'])) {
                $type_config[$k]['labels_name'] = implode(',', $type_config[$k]['labels_name']);
                $type_config[$k]['labels'] = implode(',', $type_config[$k]['labels']);
            } else {
//                unset($type_config[$k]);
            }
        }
//      获取下一页（page+1）的数据，如果还有就返回more = 1,反之就返回more = 0
        $more = 0;
        if(isset($pages) &&isset($maxPerPage)) {
            $pages = $pages + 1;
            $type_brand_b = db($demand)->where($where)->order($order)
                ->limit($pages * $maxPerPage, $maxPerPage)->select();
//            dump($type_brand_b);die;
            if ($type_brand_b) {
                $more = 1;
            } else {
                $more = 0;
            }
        }
        foreach ($type_config as $k =>$v){
            if(count($v) == 1){
                unset($type_config[$k]);
            }
        }
        $result = array('state' => 1, 'data' => array('list' => $type_config,'more'=>$more));
        return $result;
    }

    function getListForAdmin($filter)
    {
        $demand = $this->demand;
        //基础条件
        $type_id_a = $filter['select'];
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        $order = ["state" => "desc", 'range' => 'asc', 'create_time' => 'desc'];
        $where = "state != 0";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        if ($filter['keywords']) {
            $where .= " and (name like '%$filter[keywords]%')";
        }
        //labels条件]
        if ($type_id_a) {
            $where .= " and labels like '%$type_id_a%'";
        }
        $type_config = db($demand)->where($where)->order($order)->limit($pages * $maxPerPage, $maxPerPage)->select();
        $labels_name = db($demand . '_label')->field('label_id,cn,en')->where("state =1")->select();
        //再计算一次去掉不存在type_id的
        foreach ($type_config as $k => $v) {
            if (!empty($v['imgurls'])) {
                $img = explode(',', $v['imgurls'])[0];
                $type_config[$k]['imgurl'] = $img;
            }
            if ($v['state'] == 1) {
                $type_config[$k]['released'] = $v['state'];
                unset($type_config[$k]['state']);
            } else {
                $type_config[$k]['released'] = 0;
                unset($type_config[$k]['state']);
            }
            if ($v['labels'] != null) {
                $type_config[$k]['labels'] = explode(',', $v['labels']);
            }
            $type_config[$k]['price_min'] = $this->getPriceByProductId($v[$demand . '_id'])['price_min'];
            $type_config[$k]['price_max'] = $this->getPriceByProductId($v[$demand . '_id'])['price_max'];
            $detail = $this->detail_getList(['select' => $v[$demand . '_id']]);
            $type_config[$k]['detail_amount'] = count($detail['data']['list']);
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels']) && $v['labels'] && is_array($v['labels'])) {
                if($type_id_a && strpos(',',$type_id_a) !== false && !in_array($type_id_a,$v['labels'])){
                    unset($type_config[$k]);
                    continue;
                }
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $type_config[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
            }
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels_name']) && isset($v['labels'])) {
                $type_config[$k]['labels_name'] = implode(',', $type_config[$k]['labels_name']);
                $type_config[$k]['labels'] = implode(',', $type_config[$k]['labels']);
            } else {
//                unset($type_config[$k]);
            }
        }
        //获取下一页（page+1）的数据，如果还有就返回more = 1,反之就返回more = 0
        $pages = $pages + 1;
        $type_brand_b = db($demand)->where($where)->order($order)
            ->limit($pages * $maxPerPage, $maxPerPage)->select();
//        dump($type_brand_b);die;
        if ($type_brand_b) {
            $more = 1;
        } else {
            $more = 0;
        }
        $result = array('state' => 1, 'data' => array('list' => $type_config, 'more' => $more, 'maxPerPage' => $maxPerPage));
        return $result;
    }

    function range($ranges)
    {
        $demand = $this->demand;
        if (!$ranges) return ['state' => 0, 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $demand_id) {
            $where = [$demand . '_id' => $demand_id, 'state' => ['<>', 0]];
            $update = ['range' => $range];
            db($demand)->where($where)->update($update);
        }
        model('action')->add('product_range',$demand.'_id',$ranges);
        return ['state' => 1];
    }
    //配置层config
    //新增配置
    function config_create($data,$template = null)
    {
        $demand = $this->demand;
        $user_id = model('user')->getUserId();
        //判断是否是rank为0的
        if($data) {
            $labellist = db($demand.'_label')->where("label_id in($data)")->select();
            foreach ($labellist as $k =>$v){
                if($v['rank'] == 0){
                    $label_id[] = $v['label_id'];
                    //查询出所有子集
                    $info = db($demand.'_label')->where("category = $v[category]")->field('label_id')->select();
                    foreach ($info as $kk =>$vv){
                        $id[] = $vv['label_id'];
                    }
                }
            }
        }
        if(isset($id)) {
            $id = implode(',',$id);
            $data = $data.','.$id;
            $data = explode(',',$data);
            $data = implode(',',array_unique($data));
        }
        if($template){
            $info['template'] = 1;
        }
        $info['confing_descripton'] = ' ';
        $info['user_id'] = $user_id;
        $info['create_time'] = time();
        $info['labels'] = $data;
        $where = "state = 1 and (labels = ''";
        if ($info['labels']) {
            $where .= " or labels in ($info[labels])";
        }
        $where .= ' )';
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        //取出最后一层
        $config_a = db($demand . '_config')->where($where)->order('`range` desc')->find();
        if (!$config_a) {
            if ($info['labels']) {
                $info['range'] = 1;

            } else {
                $info['range'] = 0;
            }
        } else {
            $info['range'] = $config_a['range'] + 1;
        }
        //新增一层
        $info['state'] = 1;
        if (!db($demand . '_config')->insertGetId($info)) {
            return array('state' => 0, 'errormsg' => 'create error', 'errorcode' => '');
        }
        model('action')->add('config_create','labels',$data);
        return array('state' => 1, 'errormsg' => 'ok');
    }

    //删除配置
    function config_remove($config_id)
    {
        $demand = $this->demand;
        if (!$config_id > 0) {
            return array('state' => 0, 'errormsg' => 'config id incorrect', 'errorcode' => '');
        }
        $data['state'] = 0;
        $where = "config_id in($config_id)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['user_id'] = model('user')->getUserId();
        $res = db($demand . '_config')->where($where)->update($data);
        //删除配置后对应的配置参数也该删除
        if ($res) {
            db($demand . '_config_option')->where($where)->update($data);
        }
        model('action')->add('config_remove','config_id',$config_id);
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }

    function config_release($config_id, $release)
    {
        $demand = $this->demand;
        if (!$config_id > 0) {
            return array('state' => 0, 'errormsg' => 'config id incorrect', 'errorcode' => '');
        }
        if ($release) {
            $data['state'] = 1;
        } else {
            $data['state'] = 2;
        }
        $where = "config_id in($config_id)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['user_id'] = model('user')->getUserId();
        $res = db($demand . '_config')->where($where)->update($data);
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'release error');
        }
        model('action')->add('config_release','config_id',$config_id);
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }

    function config_rename($type_config_id, $config_name, $lang)
    {
        $demand = $this->demand;
        $user_id = model('user')->getUserId();
        if (!$lang) {
            $lang = 'cn';
        }
        if (!$type_config_id > 0) {
            return array('state' => 0, 'errormsg' => 'type_config id incorrect', 'errorcode' => '');
        }
        $where = "config_id = '$type_config_id'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['config_name_' . $lang] = $config_name;
        $data['user_id'] = $user_id;
        db($demand . '_config')->where($where)->update($data);
        model('action')->add('config_rename','config_name',$config_name);
        return array('state' => 1, 'errorcode' => 'ok',);
    }

    //配置list
    function config_getList($filter)
    {
        $demand = $this->demand;
        //基础条件
        if ($filter['labels']) {
            $labels = $filter['labels'];
        } else {
            $labels = '';
        }
//        if (isset($filter['page']) && $filter['page'] != '') {
//            $pages = $filter['page'] - 1;
//        } else {
//            $pages = 0;
//        }
//        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
//            $maxPerPage = $filter['maxPerPage'];
//        } else {
//            $maxPerPage = 10;
//        }
        $order = ['range', 'create_time' => 'desc'];
        $where = 'state = 1';
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        //labels条件
        $where .= " and (labels = ''";
        if ($labels) {
            $labels = explode(',', $labels);
            foreach ($labels as $k => $v) {
                $where .= "  or labels like ('%$v%')";
            }
        }
        $where .= ' )';
        $configlist = db($demand . "_config")
            ->where($where)->order($order)
            ->select();

        if (!count($configlist)) {
            return array('state' => 1, 'data' => array('list' => []));
        }
        //根据labels重新排序
        $configlist = $this->sortArrByField($configlist, 'labels', 'ASC');
        $config_optionlist = db($demand . '_config_option')
            ->where('state = 1')
            ->field('config_id,config_option_id,option_name_cn,option_name_en')
            ->order('`range`,option_name_cn')->select();
//            $config_optionlist = $this->sortArrByField($config_optionlist,'option_name_cn','ASC');
        $labels_name = db($demand . '_label')->field('label_id,cn,en')->where("state =1")->select();
        foreach ($configlist as $k => $v) {
            if ($v['state'] == 1) {
                $configlist[$k]['released'] = 1;
            } else {
                $configlist[$k]['released'] = 0;
            }
            unset($configlist[$k]['state']);
        }
        foreach ($configlist as $k => $v) {
            foreach ($config_optionlist as $kk => $vv) {
                if ($v['config_id'] == $vv['config_id']) {
                    $configlist[$k]['config_options'][] = $vv;
                }
            }
        }
        foreach ($configlist as $k => $v) {
            if ($v['labels'] != null) {
                $configlist[$k]['labels'] = explode(',', $v['labels']);
            }
        }
        foreach ($configlist as $k => $v) {
            if (is_array($v['labels'])) {
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $configlist[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
                $configlist[$k]['labels'] = implode(',', $configlist[$k]['labels']);
            }
            if (isset($configlist[$k]['labels_name'])) {
                $configlist[$k]['labels_name'] = implode(',', $configlist[$k]['labels_name']);
            }
        }
        //获取下一页（page+1）的数据，如果还有就返回more = 1,反之就返回more = 0
//        $pages = $pages + 1;
//        $type_brand_b = db($demand . "_config")->where($where)
//            ->order($order)->limit($pages * $maxPerPage, $maxPerPage)->select();
//        if (count($type_brand_b)) {
//            $more = 1;
//        } else {
//            $more = 0;
//        }
        $result = array('state' => 1, 'data' => array('list' => $configlist));
        return $result;
    }

    function config_adminList($filter)
    {
        $demand = $this->demand;
        //基础条件
        if ($filter['labels']) {
            $labels = $filter['labels'];
        } else {
            $labels = '';
        }
//        if (isset($filter['page']) && $filter['page'] != '') {
//            $pages = $filter['page'] - 1;
//        } else {
//            $pages = 0;
//        }
//        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
//            $maxPerPage = $filter['maxPerPage'];
//        } else {
//            $maxPerPage = 10;
//        }
        $order = ['range', 'labels' => 'desc'];
        $where = 'state != 0';
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        //labels条件
        $where .= " and (labels = ''";
        if ($labels) {
            $labels = explode(',', $labels);
            foreach ($labels as $k => $v) {
                $where .= "  or labels like ('%$v%')";
            }
        }
        $where .= ' )';
//            echo $where;die;
        $configlist = db($demand . "_config")
            ->where($where)->order($order)
            ->select();
        if (!count($configlist)) {
            return array('state' => 1, 'data' => array('list' => []));
        }
        //根据labels重新排序
//        $configlist = $this->sortArrByField($configlist,'labels','ASC');
        $config_optionlist = db($demand . '_config_option')
            ->field('config_id,config_option_id,option_name_cn,option_name_en')
            ->where('state =1')->order('`range`,option_name_cn')->select();
        $labels_name = db($demand . '_label')->field('label_id,cn,en')->where("state =1")->select();
        foreach ($configlist as $k => $v) {
            if ($v['state'] == 2) {
                $configlist[$k]['released'] = 0;
            } else {
                $configlist[$k]['released'] = 1;
            }
            unset($configlist[$k]['state']);
        }
        foreach ($configlist as $k => $v) {
            foreach ($config_optionlist as $kk => $vv) {
                if ($v['config_id'] == $vv['config_id']) {
                    $configlist[$k]['config_options'][] = $vv;
                }
            }
        }
        foreach ($configlist as $k => $v) {
            if ($v['labels'] != null) {
                $configlist[$k]['labels'] = explode(',', $v['labels']);
            }
        }
        foreach ($configlist as $k => $v) {
            if (is_array($v['labels'])) {
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $configlist[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
                $configlist[$k]['labels'] = implode(',', $configlist[$k]['labels']);
            }
            if (isset($configlist[$k]['labels_name'])) {
                $configlist[$k]['labels_name'] = implode(',', $configlist[$k]['labels_name']);
            }

        }
//            dump($configlist);die;
        //获取下一页（page+1）的数据，如果还有就返回more = 1,反之就返回more = 0
//        $pages = $pages + 1;
//        $type_brand_b = db($demand . "_config")->where($where)
//            ->order($order)->limit($pages * $maxPerPage, $maxPerPage)->select();
//
//        if (count($type_brand_b)) {
//            $more = 1;
//        } else {
//            $more = 0;
//        }
        $result = array('state' => 1, 'data' => array('list' => $configlist));

        return $result;
    }

    //config排序
    function config_range($ranges)
    {
        $demand = $this->demand;
        if (!$ranges) return ['state' => 0, 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $config_id) {
            $where = ['config_id' => $config_id, 'state' => ['<>', 0]];
            $update = ['range' => $range];
            db($demand . '_config')->where($where)->update($update);
        }
        model('action')->add('config_range','config_id',$ranges);
        return ['state' => 1];
    }

    function config_option_range($config_id, $ranges)
    {
        $demand = $this->demand;
        if (!$ranges) return ['state' => 0, 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $config_option_id) {
            $where = ['config_id' => $config_id, 'config_option_id' => $config_option_id, 'state' => ['<>', 0]];
            $update = ['range' => $range];
            db($demand . '_config_option')->where($where)->update($update);
        }
        model('action')->add('config_option_range','config_option_id',$ranges);
        return ['state' => 1];
    }
    //配置导航层config_option
    //创建一个新的配置参数
    function config_option_create($config_id, $config_option_name, $lang)
    {
        if (!$lang) {
            $lang = 'cn';
        }
        $user_id = model('user')->getUserId();
        $demand = $this->demand;
        //判断输入数据完整性
        if (!$config_id > 0) {
            return array('state' => 0, 'errormsg' => 'config id incorrect', 'errorcode' => '');
        }
        $data['create_time'] = time();
        $data['state'] = 1;
        $optioninfo = db($demand . '_config_option')->where("state = 1")->order('`range` asc')->select();
        if (!$optioninfo) {
            $data['range'] = 1;
        } else {
            $data['range'] = $optioninfo[0]['range'] + 1;
        }
        $data['config_id'] = $config_id;
        $data['option_name_' . $lang] = $config_option_name;
        $data['user_id'] = $user_id;
        $where = "config_id = $config_id and state =1";
        if ($this->unit_id) {
            $data['unit_id'] = $this->unit_id;
            $where .= " and unit_id = $this->unit_id";
        }
        db($demand . '_config_option')->insert($data);
        $config_option = db($demand . '_config_option')->where($where)->select();
        $config_option = $this->sortArrByField($config_option, 'option_name_cn', 'ASC');
        model('action')->add('config_option_create','option_name',$config_option_name);
        return array('state' => 1, 'errormsg' => 'ok', 'data' => array('config_options' => $config_option));
    }

    //删除配置参数
    function config_option_remove($config_option_id)
    {
        $user_id = model('user')->getUserId();
        $demand = $this->demand;
        if (!$config_option_id) {
            return array('state' => 0, 'errormsg' => 'need config_option_id');
        }
        $where = "config_option_id = '$config_option_id'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['state'] = 0;
        $data['user_id'] = $user_id;
        db($demand . '_config_option')->where($where)->update($data);
        model('action')->add('config_option_remove','config_option_id',$config_option_id);
        return array('state' => 1, 'errormsg' => 'ok');
    }

    function config_option_clean($config_id)
    {
        $user_id = model('user')->getUserId();
        $demand = $this->demand;
        if (!$config_id) {
            return array('state' => 0, 'errormsg' => 'need config_option_id');
        }
        $where = "config_id = $config_id";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['state'] = 0;
        $data['user_id'] = $user_id;
        $res = db($demand . '_config_option')->where($where)->update($data);
        if (!$res) {
            return array('state' => 1, 'errormsg' => 'remove error');
        }
        model('action')->add('config_option_clean','config_id',$config_id);
        return array('state' => 1, 'errormsg' => 'ok');
    }

    function getOptionListByConfigId($config_id)
    {
        $demand = $this->demand;
        $where = "config_id = '$config_id' and state = '1'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $config_option = db($demand . '_config_option')->where($where)->order("option_name_cn", "`range`")->select();
        return $config_option;
    }

    //型号层detail
    function detail_create($data)
    {
        //检查错误情况
        $demand = $this->demand;
        $brand_id = $data[$demand . '_id'];
        if (!($brand_id > 0)) {
            return array('state' => 0, 'errormsg' => 'brand id error');
        }
        if (strpos($data['price'], ',')) {
            $data['price'] = json_decode($data['price'], 1);
            $data['price'] = implode(',', $data['price']);
        }
        $where = $demand . "_id = $brand_id and state != 0";
        if ($this->unit_id) {
            $unit_id = $this->unit_id;
            $where .= " and unit_id = $unit_id";
        } else {
            $unit_id = null;
        }
        if(!isset($data['deposit'])) $data['deposit']=null;
        if(!isset($data['admin_only']))$data['admin_only']=null;
        if(!isset($data['discount_price']))$data['discount_price']=null;
        if(!isset($data['discount']))$data['discount']=null;
        //创建detail主数据
        $user_id = model('user')->getUserId();
        $addArray = array(
            $demand . '_id' => $brand_id,
            'create_time' => time(),
            'user_id' => $user_id,
            'state' => 2,
            'price' => $data['price'],
            'discount' => (int)$data['discount'],
            'deposit' => $data['deposit'],
            'detail_code' => $data['detail_code'],
            'admin_only' => $data['admin_only'],
            'discount_price' => $data['discount_price'],
            'unit_id' => $unit_id
        );
        //判断必要参数是否填写
        foreach ($data as $key => $value) {
            if ($key == 'price' && $value == '') {
                return array('state' => 0, 'errormsg' => 'detail data null');
            }
        }
        //检查此product是否已有该detail
        $detail_option = json_decode($data['options'], 1);
        $detail_id = db($demand . '_detail')->field("detail_id")->where($where)->select();
        $content = [];
        foreach ($detail_id as $k => $v) {
            $detailId = $v['detail_id'];
            //找到已有所有option
            if (!$unit_id) {
                $option = db($demand . "_detail_option")->field('option_name_cn,option_name_en,config_id')
                    ->where("detail_id = '$detailId' and state != 0")->select();
            } else {
                $option = db($demand . "_detail_option")->field('option_name_cn,option_name_en,config_id')
                    ->where("detail_id = '$detailId' and state != 0 and unit_id = $unit_id")->select();
            }
            //检查是否重复
            foreach ($option as $kk => $vv) {
                $content[$vv['config_id']]['option_name_cn'] = $vv['option_name_cn'];
            }
            if ($content == $detail_option || (empty($detail_option) && empty($option))) {
                return array('state' => 0, 'errormsg' => 'detail exist');
            }
        }
        $id = db($demand . '_detail')->insertGetId($addArray);
        model('action')->add('detail_create','price',$data['price']);
        //创建配置数据
        $dataList = array();
        $en = '';
        if (!empty($detail_option)) {
            foreach ($detail_option as $k_k => $v_v) {
                if (isset($v_v['option_name_en'])) {
                    $en = $v_v['option_name_en'];
                }
                $dataList[] = array(
                    'option_name_cn' => $v_v['option_name_cn'],
                    'option_name_en' => $en,
                    'detail_id' => $id,
                    "config_id" => $k_k,
                    'state' => 1,
                    'user_id' => $user_id,
                    'unit_id' => $unit_id
                );
                model('action')->add('detail_option_create','option_name_cn',$v_v['option_name_cn']);
            }
            if (!$id = db($demand . '_detail_option')->insertAll($dataList)) {
                return array('state' => 0, 'errormsg' => 'insert error');
            }
        }
        return array('state' => 1, 'errormsg' => 'ok', 'data' => array('detail_options' => $dataList));
    }

    function detail_remove($product_detail_id)
    {
        //判断是否有admin_product身份
        $demand = $this->demand;
        if (!($product_detail_id > 0)) {
            return array('state' => 0, 'errormsg' => 'detail id error');
        }
        $where = "detail_id in ($product_detail_id)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $data['state'] = 0;
        $ret = db($demand . '_detail')->where($where)->update($data);
        model('action')->add('detail_remove','detail_id',$product_detail_id);
        db($demand . '_detail_option')->where($where)->update($data);
        model('action')->add('detail_option_remove','detail_id',$product_detail_id);
        if ($ret) {
            $ret = array('data' => array('info' => ''), 'state' => 1, 'errormsg' => '删除成功');
            return $ret;
        }
    }

    function detail_release($product_detail_id, $release)
    {
        $demand = $this->demand;
        //判断输入数据是否完整
        if (!$product_detail_id > 0) {
            return array('state' => 0, 'errormsg' => 'detail id error');
        }
        if ($release) {
            $data['state'] = 1;
        } else {
            $data['state'] = 2;
        }
        $where = "detail_id in ($product_detail_id)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        db($demand . '_detail')->where($where)->update($data);
        model('action')->add('detail_release','release',$release);
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }

    function detail_adminList($filter)
    {
        $demand = $this->demand;
//            基础条件
        if (!$filter['select']) {
            return array('state' => 0, 'errormsg' => 'not id');
        }
        $demand_id = $filter['select'];
        //基础条件
        //先找到demand下所有detail
        $where_demand_id = $demand . "_id";
        $where = "$where_demand_id = '$demand_id' and state != 0";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $detail = db($demand . '_detail')->where($where)->order('`range`')->select();
        //再找到各自detail下的option
        if (!$detail) {
            return array('state' => 1, 'data' => array('list' => $detail));
        }
        foreach ($detail as $k => $v) {
            //开放/关闭状态
            if ($v['state'] == 1) {
                $detail[$k]['released'] = $v['state'];
                unset($detail[$k]['state']);
            } else {
                $detail[$k]['released'] = 0;
                unset($detail[$k]['state']);
            }
            if ($v['discount']) {
                $detail[$k]['total_fee_original'] = $v['price'] / $v['discount'];
            }
            if (strpos($v['price'], ',')) {
                $detail[$k]['price'] = explode(',', $v['price']);
                foreach ($detail[$k]['price'] as $p => $c) {
                    $detail[$k]['price'][$p] = ($c / 100);
                }
                $price = array_chunk($detail[$k]['price'], 3);
                $detail[$k]['price'] = implode(',', $price[0]) . '<br/>' . implode(',', $price[1]);
            }
            $detail_id = $v['detail_id'];
            if (!$this->unit_id) {
                $detail_option = db($demand . '_detail_option')->where("detail_id = '$detail_id' and state = 1")->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->order("`range`,option_name_cn")->select();
            } else {
                $detail_option = db($demand . '_detail_option')->where("unit_id = $this->unit_id")->where("detail_id = '$detail_id' and state = 1")->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->order("`range`,option_name_cn")->select();
            }
            foreach ($detail_option as $key => $value) {
                if ($value['detail_id'] == $detail_id && !empty($value['config_id'])) {
                    if (!$this->unit_id) {
                        $config = db($demand . '_config')->field('config_id,config_name_cn,config_name_en')->where("config_id = $value[config_id]")->find();
                    } else {
                        $config = db($demand . '_config')->field('config_id,config_name_cn,config_name_en')->where("unit_id = $this->unit_id")->where("config_id = $value[config_id]")->find();
                    }
                    if ($value['config_id'] == $config['config_id']) {
                        $detail_option[$key]['config_name_cn'] = $config['config_name_cn'];
                        $detail_option[$key]['config_name_en'] = $config['config_name_en'];
                    }
                    $detail[$k]['options'][] = $detail_option[$key];
                }
            }
        }
        //获取下一页（page+1）的数据，如果还有就返回more = 1,反之就返回more = 0
        $result = array('state' => 1, 'data' => array('list' => $detail));
        return $result;
    }

    function detail_getList($filter, $admin_only = 0)
    {
        $demand = $this->demand;
//            基础条件
        if (!$filter['select']) {
            return array('state' => 0, 'errormsg' => 'not id');
        }
        if ($admin_only) {
            $where = 'state = 1 and isnull(admin_only)';
        } else {
            $where = 'state = 1 ';
        }
        $demand_id = $filter['select'];
        //基础条件
        //先找到demand下所有detail
        $where_demand_id = $demand . "_id";
        $where .= " and $where_demand_id = '$demand_id'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $detail = db($demand . '_detail')->where($where)->order('`range`')->select();
        //再找到各自detail下的option
        foreach ($detail as $k => $v) {
            //开放/关闭状态
            if ($v['state'] == 1) {
                $detail[$k]['released'] = $v['state'];
                unset($detail[$k]['state']);
            } else {
                $detail[$k]['released'] = 0;
                unset($detail[$k]['state']);
            }
            $detail_id = $v['detail_id'];
            if (!$this->unit_id) {
                $detail_option = db($demand . '_detail_option')->where("detail_id = '$detail_id' and state = 1")->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->order("`range`,option_name_cn")->select();
            } else {
                $detail_option = db($demand . '_detail_option')->where("unit_id = $this->unit_id")->where("detail_id = '$detail_id' and state = 1")->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->order("`range`,option_name_cn")->select();
            }
            foreach ($detail_option as $key => $value) {
                $detail[$k]['options'][] = $value;
                $config_ids[] = $value['config_id'];
            }
        }
        if (isset($config_ids)) {
            $config_ids = array_unique($config_ids);
            $config_ids = implode(",", $config_ids);
            $where = "config_id  in($config_ids)";
            if ($this->unit_id) {
                $where .= " and unit_id = $this->unit_id";
            }
            $res = db($demand . '_config')->where($where)->order('`range`')->select();
            $config = [];
            foreach ($res as $i => $value) {
                $config[$value['config_id']]['config_name_cn'] = $value['config_name_cn'];
                $config[$value['config_id']]['config_name_en'] = $value['config_name_en'];
            }
            foreach ($detail as $k => $v) {
                if (!isset($v['options'])) {
                    continue;
                }
                foreach ($v['options'] as $i => $vv) {
                    $id = $vv['config_id'];
                    if (!isset($config[$id])) {
                        unset($detail[$k]['options'][$i]);
                    } else {
                        $detail[$k]['options'][$i]['config_name_cn'] = $config[$id]['config_name_cn'];
                        $detail[$k]['options'][$i]['config_name_en'] = $config[$id]['config_name_en'];
                    }
                }
            }
        }

//            dump($detail);die;
        //获取下一页（page+1）的数据，如果还有就返回more = 1,反之就返回more = 0
        $result = array('state' => 1, 'data' => array('list' => $detail));
        return $result;
    }

    function detail_range($ranges)
    {
        $demand = $this->demand;
        if (!$ranges) return ['state' => 0, 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $detail_id) {
            $where = ['detail_id' => $detail_id, 'state' => ['<>', 0]];
            $update = ['range' => $range];
            db($demand . '_detail')->where($where)->update($update);
        }
        model('action')->add('detail_range','detail_id',$ranges);
        return ['state' => 1];
    }

    function detail_option_range($detail_id, $ranges)
    {
        $demand = $this->demand;
        if (!$ranges) return ['state' => 0, 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $detail_option_id) {
            $where = ['detail_id' => $detail_id, 'detail_option_id' => $detail_option_id, 'state' => ['<>', 0]];
            $update = ['range' => $range];
            db($demand . '_detail_option')->where($where)->update($update);
        }
        model('action')->add('detail_option_range','detail_option_id',$ranges);
        return ['state' => 1];
    }

    //根据label_id取到label_name
    function getLabelNameById($labels)
    {
        $demand = $this->demand;
        $where = "label_id in ($labels)";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $labelinfo = db($demand . "_label")->where($where)->select();
        foreach ($labelinfo as $k => $v) {
            $cn[$k] = $v['cn'];
        }
        return array('state' => 1, 'data' => array('label_name' => implode(',', $cn)));
    }

    //根据demand_id取到价格区间
    function getPriceByProductId($product_id)
    {
        $demand = $this->demand;
        //先找到demand下所有detail
        $where_demand_id = $demand . "_id";
        $where = "$where_demand_id = '$product_id' and state = 1";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $order = "price";
        $detail = db($demand . '_detail')->where($where)->order($order)->select();
        if (count($detail)) {
            $price_min = $detail[0]['price'];
            $price_max = $detail[count($detail) - 1]['price'];
        } else {
            $price_min = 0;
            $price_max = 0;
        }
        return array('state' => 1, 'price_min' => $price_min, 'price_max' => $price_max);
    }

    //收银员订单生成
    public function orderCreate($detail, $address_id)
    {
        $demand = $this->demand;
        //判断是否登录
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => 'user_id not find');
        }
        if (!$detail) {
            return array('state' => 0, 'errormsg' => 'detail not find');
        }
        $data['user_id'] = $userId = $this->userId;
        $where = "user_id = '$userId'";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $userinfo = db('user_member')->where($where)->order('class desc')->select();
        //获得card_code
        $cardinfo = db('user_card')->where($where)->order("create_time desc")->select();
        if ($userinfo) {
            //计算会员卡时效
            foreach ($userinfo as $k => $v) {
                if (!(time() - $v['create_time']) / 86400 > $v['temporality'] || !$v['temporality']) {
                    $user_info[] = $v;
                }
            }
        }
        //计算价格(以分为单位)
        $price = $this->reckonPrice($detail, $cardinfo[0]['card_code'])['data']['price'];
        //-------------------------------------
        $data['detail'] = $detail;
        $data['state'] = 1;
        //配置文件取当前class的id
        $config = $this->config;
        $data['class'] = $config[$demand]['id'];
        //-------------------------------------
        $data['receive_id'] = $address_id;
        //price：先找到coupon优惠信息,算出优惠价格,再拼接menber优惠的价格形成字符[原价,coupon优惠价格,menber优惠价格],例:[800,-100,-100]、[800,0,0]
        $data['create_time'] = time();
        //优惠前的价格，优惠后的价格
        $data['total_fee'] = $this->reckonPrice($detail, $cardinfo[0]['card_code'])['data']['price'];
        //把数据传入order生成订单接口
        $ret = model('order')->add($demand, $data);
        model('action')->add('order_create','order_id',$ret['data']['info']['order_id']);
        return $ret;
    }

    function adminOrderCreate($detail, $member)
    {
        $demand = $this->demand;
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => 'user_id not find');
        }
        $data['admin_user_id'] = $this->userId;
        $data['detail'] = $detail;
        $data['state'] = 1;
        //配置文件取当前class的id
        $config = $this->config;
        $data['product'] = $config[$demand]['id'];
        if ($member) {
            //找到member信息
//            $prefix=config('database.prefix');
            $where = "u.card_code = '$member' AND u.state = '1'";
            if ($this->unit_id) {
                $where .= " and unit_id = $this->unit_id";
            }
            $memberinfo = db('user_card')->alias('u')
                ->join("user_member m", 'm.user_id = u.user_id')
                ->where($where)->order('m.class desc')->select();
            if ($memberinfo) {
                //计算会员卡时效
                foreach ($memberinfo as $k => $v) {
                    if (!(time() - $v['create_time']) / 86400 > $v['temporality'] || !$v['temporality']) {
                        $user_info[] = $v;
                    }
                }
                $data['member_id'] = $memberinfo[0]['card_code'];
                $data['user_id'] = $memberinfo[0]['user_id'];
            }
        }
        if (!$member) {
            $data['member_id'] = 0;
        }
        $tfee = $this->reckonPrice($detail, $data['member_id']);
        if (!$tfee['state']) {
            return $tfee;
        }
//        $data[DISCOUNT] = $tfee['data'][info][discount];
        $data['total_fee_original'] = $tfee['data']['info']['original_fee'];
        $data['total_fee'] = $tfee['data']['price'];
        $data['create_time'] = time();
        $ret = model('order')->add($demand, $data);
        model('action')->add('admin_order_create','order_id',$ret['data']['info']['order_id']);
        return $ret;
    }


    //计算价格
    function reckonPrice($detail, $member, $coupon = 0)
    {
        $demand = $this->demand;
        //通过card_code找到user_id
        if ($member) {
            $card_info = model('card')->getUserIdByCode($member);
            if (!$card_info['state']) {
                return $card_info;
            }
            $user_id = $card_info['data']['user_id'];
            $discount = model('member')->getDiscountByUserId($demand, $user_id);
            if (!$discount['state']) {
                return $discount;
            }
        }
        //获取detail信息
        $detail_n = json_decode($detail, 1);
        if (!$detail_n) {
            return array('state' => 0, 'errormsg' => 'detail error');
        }
        //取出id
        $detail_key = array_keys($detail_n);

        $detail_key = implode(',', $detail_key);
        //查找detail信息
        if ($demand == 'book') {
            $where = $demand . "_id in ($detail_key)";
            if ($this->unit_id) {
                $where .= " and unit_id = $this->unit_id";
            }
            $product_info = db($demand)->where($where)->select();
            //计算各个商品价格
            foreach ($product_info as $k => $v) {
                if (!$v['tfee']) {
                    //如果购买书籍里有未设置价格的书籍，则返回错误。
                    return array('state' => 0, 'errormsg' => 'need set price');
                }
                $num = $detail_n[$v['book_id']];
                $price[] = $num * $v['tfee'];
            }
        } else {
            $where = "detail_id in ($detail_key)";
            if ($this->unit_id) {
                $where .= " and unit_id = $this->unit_id";
            }
            $product_info = db($demand . "_detail")->where($where)->select();
            //计算各个商品价格
            foreach ($product_info as $k => $v) {
                if (!$v['price']) {
                    //如果里有未设置价格的，则返回错误。
                    return array('state' => 0, 'errormsg' => 'need set price');
                }
                $num = $detail_n[$v['detail_id']];
                $price[] = $num * $v['price'];
            }
        }
        $price = $price_old = array_sum($price);
        //该会员折扣
        if ($member) $price = $price * $discount['info']['discount'];
        if (!$price) return array('state' => 0, 'errormsg' => 'reckon_price error');
        //最后进行价格确认
        if ($price <= 0) return array('state' => 0, 'errormsg' => 'reckon_price error');
        //最终价格
        $info['total_fee'] = $price;
        //折扣
        if ($member) $info['discount'] = $discount['info']['discount'];
        //优惠了多少钱
        $info['discount_fee'] = $price_old - $price;
        //原始价格original
        $info['original_fee'] = $price_old;
        //user_name
        $info['user_name'] = model('user')->getInfoById($user_id)['user_name'];
        //会员等级
        if ($member) {
            $info['intro'] = $discount['info']['intro'];
            //会员卡余额
            $info['balance'] = model('account')->getBalanceByUserId($user_id)['data']['balance'];
        }
        //返回总价
        return array('state' => 1, 'data' => array('price' => $price, 'info' => $info));
    }

    //demand统计数据
    function statisticsToday($filter, $statistics)
    {
        $demand = $this->demand;
        //当前时间区间
        $date = strtotime(date('Ymd')); //今天0点开始时间
        $time = strtotime(date('Ymd')) + 86400; //今天24点结束时间
        $config = $this->config;
        $class_id = $config[$demand]['id'];
        $prefix = config('database.prefix');
        $where = "o.class = '$class_id' AND o.state = 1 and o.create_time >= '$date' and o.create_time <= '$time'";
        if ($this->unit_id) {
            $where .= " and o.unit_id = $this->unit_id";
        }
        $order_info = db('order')->alias('o')
            ->join($prefix . 'pay p', 'p.order_id = o.order_id')
            ->where($where)->order("o.create_time desc")->select();
        foreach ($order_info as $k => $v) {
            $detail = json_decode($v['detail'], 1);
            //今日订单金额总和
            $statistics['total_fee'] += $v['total_fee'];
            //订单退款
            $order_id = $v['order_id'];
            $refund = db('pay_refund')->where("order_id = '$order_id'")->select();
            $refund_order = '';
            foreach ($refund as $k_k => $v_v) {
                $refund_order += $v_v['total_fee'];
            }
            $statistics['refund'] += $refund_order;
            //支付渠道
            switch ($v['channel']) {
                case 1:
                    $record[$k]['cashpay'] = 1;
                    break;
                case 2:
                    $record[$k]['accountpay'] = 1;
                    break;
                default:
                    switch ((int)($v['channel'] / 100)) {
                        case 1:
                            $record[$k]['wxpay'] = 1;
                            break;
                        case 2:
                            $record[$k]['alipay'] = 1;
                            break;
                    }
            }
        }

        foreach ($record as $k => $v) {
            foreach ($v as $key => $value) {
                //现金
                $refund = '';
                $cashpay_refund_id = '';
                if ($key == 'cashpay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = db('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['total_fee'];
                    }
                    $statistics['refund_cash'] += $cashpay_refund;
                    $statistics['cash'] += $order_info[$k]['total_fee'];
                }
                //微信
                if ($key == 'wxpay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = db('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['total_fee'];
                    }
                    $statistics['refund_wxpay'] += $cashpay_refund;
                    $statistics['wxpay'] += $order_info[$k]['total_fee'];
                }
                //alipay
                if ($key == 'alipay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = db('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['total_fee'];
                    }
                    $statistics['refund_alipay'] += $cashpay_refund;
                    $statistics['alipay'] += $order_info[$k]['total_fee'];
                }
                //刷卡
                if ($key == 'accountpay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = db('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['total_fee'];
                    }
                    $statistics['refund_accountpay'] += $cashpay_refund;
                    $statistics['accountpay'] += $order_info[$k]['total_fee'];
                }
            }
        }
        return array('state' => 1, 'data' => array('info' => $statistics));
    }

    //今日订单
    function getListToday($filter,$unpaid,$channel)
    {
        $demand = $this->demand;
        $demand_order = model('order')->getListToday($filter,$demand,$unpaid,$channel);
        if (!$demand_order['state']) {
            return $demand_order;
        }
        foreach ($demand_order['data']['list'] as $k => $v) {
            $detail = json_decode($v['detail'], 1);
            $demand_info = '';
            $num = '';
            $num_a = '';
            foreach ($detail as $key => $value) {
                $num[] = $value;
                $num_a = $value;
                //找到每个detail的价格
                $detailinfo = $this->getInfo($key);
                $demand_info[] = $detailinfo['data']['info'];
            }
            //产品信息
            $demand_order['data']['list'][$k]['account'] = array_sum($num);
            $demand_order['data']['list'][$k]['summary'] = $demand_info[0]['name'];
            $demand_order['data']['list'][$k]['products'] = $demand_info;
            foreach ($demand_info as $k_k => $v_v) {
                $demand_order['data']['list'][$k]['products'][$k_k]['amount'] = $num_a;
            }
            $demand_order['data']['list'][$k]['create_time'] = timeString($v['create_time']);
            //支付渠道
            $order_id = $v['order_id'];
            $pay_info = db('pay')->where("order_id = '$order_id'")->find();
//            //refund退款
            $refund_info = db('pay_refund')->where("order_id = '$order_id'")->select();
            $refund = 0;
            foreach ($refund_info as $k_new => $v_new) {
                $refund += $v_new['total_fee'];
            }
            $demand_order['data']['list'][$k]['refund'] = $refund;

            //支付渠道
            switch ($pay_info['channel']) {
                case 1:
                    $demand_order['data']['list'][$k]['cashpay'] = 1;
                    break;
                case 2:
                    $demand_order['data']['list'][$k]['accountpay'] = 1;
                    break;
                default:
                    switch ((int)($v['channel'] / 100)) {
                        case 1:
                            $demand_order['data']['list'][$k]['wxpay'] = 1;
                            break;
                        case 2:
                            $demand_order['data']['list'][$k]['alipay'] = 1;
                            break;
                    }
            }
            //admin_user_name
            $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
            $demand_order['data']['list'][$k]['admin_user_name'] = $admin_user_info['user_name'];
            if (!$demand_order['data']['list'][$k]['admin_user_name']) {
                $demand_order['data']['list'][$k]['admin_user_name'] = '';
            }
            //user_name
            $user_info = model('user')->getInfoById($v['user_id']);
            $demand_order['data']['list'][$k]['user_name'] = $user_info['user_name'];
            $demand_order['data']['list'][$k]['tel'] = $user_info['tel'];
            if (!$demand_order['data']['list'][$k]['user_name']) {
                $demand_order['data']['list'][$k]['user_name'] = '';
            }
            if (!$demand_order['data']['list'][$k]['tel']) {
                $demand_order['data']['list'][$k]['tel'] = '';
            }
        }
        return array('state' => 1, 'data' => array('list' => $demand_order['data']['list'], 'more' => $demand_order['data']['more']));
    }

    //根据id获取商品信息
    function getInfo($detail_id)
    {
        $demand = $this->demand;
        $where = "detail_id = $detail_id";
        if ($this->unit_id) {
            $where .= " and unit_id = $this->unit_id";
        }
        $demandinfo = db($demand . '_detail')->field(array($demand . '_id', 'price'))->where($where)->find();
        $demand_id = $demandinfo[$demand . '_id'];
        if (!$this->unit_id) {
            $demand_info = db($demand)->where($demand . "_id = '$demand_id'")->find();
        } else {
            $demand_info = db($demand)->where("unit_id = $this->unit_id")->where($demand . "_id = '$demand_id'")->find();
        }
        $demand_info['price'] = $demandinfo['price'];
        return array('state' => 1, 'data' => array('info' => $demand_info));
    }
    //复制一个产品
    public function copy($product_id)
    {
        $demand = $this->demand;
        if(!$product_id){
            return array('state'=>0,'errormsg'=>'not id');
        }
        $product_id = explode(',',$product_id);
        foreach ($product_id as $k_k =>$v_v) {
            $info = db($demand)->where($demand . '_id = ' . $v_v)->find();
            if (!$info) {
                return array('state'=>0,'errormsg'=>'not find '.$demand);
            }
            $filer['keywords'] = $info['name'];
            $filer['select'] = $info['labels'];
            $data['name'] = input('name');
            $data['labels'] = input('label');
            $data['price'] = input('price');
            if (!$filer['keywords'] || !$filer['select']) {
                return array('state'=>0,'errormsg'=>'not find');
            }
            $res = model('product')->getList($filer,0,1)['data']['list'][0];
            $brand['name'] = $data['name'] ? $data['name'] : $res['name'];
            $brand['imgurls'] = isset($res['imgurls']) ? $res['imgurls'] : '';
            $brand['description'] = isset($res['description']) ? $res['description'] : '';
            $brand['config_description'] = isset($res['config_description']) ? $res['config_description'] : '';
            $brand['labels'] = $data['labels'] ? $data['labels'] : $filer['select'];
            $brand['highlight'] = isset($res['highlight']) ? $res['highlight'] : '';
            $brand['create_time'] = time();
            $brand['unit_id'] = isset($res['unit_id']) ? $res['unit_id'] : '';
            $brand['user_id'] = model('user')->getUserId();
            $brand['range'] = isset($res['range']) ? $res['range'] : '';
            $brand['homepage'] = isset($res['homepage']) ? $res['homepage'] : '';
            $brand['state'] = 2;
            $id = db($demand)->insertGetId($brand);
            foreach ($res['detail'] as $key => $vaule) {
                $detail[$demand . '_id'] = $id;
                $detail['user_id'] = model('user')->getUserId();
                $detail['price'] = $data['price'] ? $data['price'] : $vaule['price'];
                $detail['deposit'] = $vaule['deposit'];
                $detail['detail_code'] = $vaule['detail_code'];
                $detail['create_time'] = time();
                $detail['range'] = $vaule['range'];
                $detail['discount'] = $vaule['discount'];
                $detail['admin_only'] = $vaule['admin_only'];
                $detail['discount_none'] = $vaule['discount_none'];
                $detail['state'] = 1;
                $detail_id = db($demand . '_detail')->insertGetId($detail);
                if (!empty($vaule['options'])) {
                    foreach ($vaule['options'] as $k => $v) {
                        $option["detail_id"] = $detail_id;
                        $option["option_name_cn"] = $v['option_name_cn'];
                        $option["option_name_en"] = $v['option_name_en'];
                        $option["config_id"] = $v['config_id'];
                        $option['state'] = 1;
                        $option['user_id'] = model('user')->getUserId();
                        $option['range'] = '';
                        db($demand . '_detail_option')->insertGetId($option);
                    }
                }
            }
        }
        model('action')->add('copy',$demand.'_id',$product_id);
        return array('state'=>1);
    }

}
